package com.qby.e_commerce.service.impl;

import com.qby.e_commerce.entity.Wallet;
import com.qby.e_commerce.entity.WalletDetails;
import com.qby.e_commerce.mapper.WalletDetailsMapper;
import com.qby.e_commerce.mapper.WalletMapper;
import com.qby.e_commerce.service.WalletDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class WalletDetailsServiceImpl implements WalletDetailsService {

    @Autowired
    private WalletDetailsMapper walletDetailsMapper;
    @Autowired
    private WalletMapper walletMapper;

    /**
     * 格式：日期 + 流水
     * 示例：2021012305111300001
     *
     * @return wallet_details_id
     */
    private String generateWalletDetailsID(Integer walletId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder sb = new StringBuilder();
        sb.append(sdf.format(new Date())).append("0000").append(walletId);
        return sb.toString();
    }

    /**
     * 新增交易记录
     *
     * @param walletDetails
     * @return
     */
    @Transactional
    @Override
    public Integer addTransaction(WalletDetails walletDetails) {
        Wallet wallet = walletMapper.queryWallerbyId(walletDetails.getWalletId());
        Integer walletId = walletDetails.getWalletId();
        BigDecimal amount = walletDetails.getAmount();
        // 先更新钱包中的余额
        if (walletDetails.getTransactionMode() == 0) {   // 支出
            if (wallet.getBalance().compareTo(walletDetails.getAmount()) > -1) {
                walletMapper.updateBalance(walletId, amount.negate(), new Date());
            } else throw new IllegalArgumentException("余额不够！");     // 当支出时余额不足抛出异常
        } else if (walletDetails.getTransactionMode() == 1) {   //转入
            walletMapper.updateBalance(walletId, amount, new Date());
        }
        // 插入新的钱包流水记录
        walletDetails.setId(generateWalletDetailsID(walletId));
        walletDetails.setCreateDate(new Date());
        return walletDetailsMapper.addTransaction(walletDetails);
    }

    /**
     * 查询用户钱包金额变动明细的接口，按时间降序排列
     * @param walletId
     * @return  List<WalletDetails>
     */
    @Override
    public List<WalletDetails> queryWalletDetails(Integer walletId) {
        return walletDetailsMapper.queryWalletDetails(walletId);
    }
}
